package com.hbx.eduorder.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hbx.commonutils.JwtUtils;
import com.hbx.commonutils.R;
import com.hbx.eduorder.entity.Order;
import com.hbx.eduorder.service.OrderService;
import com.hbx.servicebase.exceptionhandler.GuliException;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 订单 前端控制器
 * </p>
 *
 * @author hbx
 * @since 2023-10-20
 */
@Api(tags = {"订单管理模块"})
@RestController
@CrossOrigin
@RequestMapping("/eduorder/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    /**
     * 生成订单 返回订单号
     * @param courseId
     * @param request
     * @return
     */
    @PostMapping("/createOrder/{courseId}")
    public R saveOrders(@PathVariable String courseId, HttpServletRequest request){
        //创建订单，返回订单号
        String orderNo = orderService.createOrders(courseId, JwtUtils.getMemberIdByJwtToken(request));
        return R.ok().data("orderId",orderNo);
    }

    /**
     * 根据订单号查询订单信息
     * @param orderNo 订单号
     * @return
     */
    @GetMapping("/getOrderInfo/{orderNo}")
    public R getOrderInfo(@PathVariable String orderNo){
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Order::getOrderNo,orderNo);
        Order order = orderService.getOne(queryWrapper);
        return R.ok().data("item",order);
    }

    /**
     * 根据课程id和用户id查询订单表中的订单状态
     * @param courseId
     * @param memberId
     * @return
     */
    @GetMapping("/isBuyCourse/{courseId}/{memberId}")
    public boolean isBuyCourse(@PathVariable String courseId,@PathVariable String memberId){
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Order::getCourseId,courseId);
        queryWrapper.eq(Order::getMemberId,memberId);
        queryWrapper.eq(Order::getStatus,"1"); // 判断是否支付 1为已支付
        int count = orderService.count(queryWrapper);
        return count > 0;
    }

}

